<template>
  <el-card shadow="never">
    <el-row>👏欢迎回来</el-row>
    <el-divider></el-divider>

    <!-- 顶部三个指标卡片 -->
    <el-row :gutter="30">
      <el-col :span="8">
        <div class="box user-box">
          <el-avatar :src="count_img"></el-avatar>
          <div>
            <p class="content-count">总用户数</p>
            <countTo :endVal="userCount"></countTo>
          </div>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="box visit-box">
          <el-avatar :src="total_img"></el-avatar>
          <div>
            <p class="content-count">总访问量</p>
            <countTo :endVal="getAnalyTicsTypeCount('VISIT')"></countTo>
          </div>
        </div>
      </el-col>

      <el-col :span="8">
        <div class="box clock-box">
          <el-avatar :src="increase_img"></el-avatar>
          <div>
            <p class="content-count">打卡数</p>
            <countTo :endVal="getAnalyTicsTypeCount('DIET_LOG')"></countTo>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-divider></el-divider>

    <!-- 两个图表 -->
    <div style="justify-content: space-between; display: flex; margin-top: 40px">
      <div style="position: relative; width: 50%; height: 400px">
        <div ref="contentEchart" style="width: 100%; height: 100%"></div>
      </div>
      <div ref="clickEchart" style="width: 40%; height: 400px"></div>
    </div>
  </el-card>
</template>

<script>
import countTo from "vue-count-to";
import * as echarts from "echarts";

export default {
  data() {
    return {
      count_img: require("@/assets/images/count.png"),
      total_img: require("@/assets/images/total.png"),
      increase_img: require("@/assets/images/increase.png"),
      userCount: 0,
      analytics: [],
      contentEchart: null,
      clickEchart: null,
      contentOption: {
        title: {
          text: "时段分布-打卡数",
          left: "left",
          top: "top",
          textStyle: { fontWeight: "bold" }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "line" }
        },
        grid: { top: "15%", bottom: "10%", left: "10%", right: "10%" },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [] // 会动态填充
        },
        yAxis: { type: "value" },
        series: [
          {
            name: "打卡数",
            type: "line",
            smooth: true,
            showSymbol: false,
            lineStyle: {
              width: 2,
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: "#43eaff" },
                { offset: 1, color: "#7347fb" }
              ])
            },
            areaStyle: {
              opacity: 1,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#dfeeff" },
                { offset: 0.5, color: "#f4f9ff" },
                { offset: 1, color: "#ffffff" }
              ])
            },
            data: []
          }
        ]
      },
      clickOption: {
        title: {
          text: "模块点击量占比",
          left: "left",
          top: "top",
          textStyle: { fontWeight: "bold" }
        },
        tooltip: {
          trigger: "item",
          formatter: p =>
            `${p.name} : ${p.percent}%<br/>点击量：${p.data.click_count}`
        },
        legend: { bottom: "5%", left: "center" },
        series: [
          {
            name: "模块占比",
            type: "pie",
            radius: ["40%", "60%"],
            data: []
          }
        ]
      }
    };
  },

  components: { countTo },

  methods: {
    getAnalyTicsTypeCount(type) {
      return this.analytics.find(item => item.eventType === type)?.count ?? 0;
    },

    /* 折线图数据统计（每小时） */
    getDietLogSeriesData() {
      const hours = Array.from({ length: 24 }, (_, i) =>
        i.toString().padStart(2, "0") + ":00"
      );
      const counts = Array(24).fill(0);

      this.analytics
        .filter(item => item.eventType === "DIET_LOG" && item.hour != null)
        .forEach(item => {
          const h = Number(item.hour);
          if (h >= 0 && h < 24) counts[h] += item.count;
        });

      return { hours, counts };
    },

    initCharts() {
      this.contentEchart = echarts.init(this.$refs.contentEchart);
      this.clickEchart = echarts.init(this.$refs.clickEchart);
      this.contentEchart.setOption(this.contentOption);
      this.clickEchart.setOption(this.clickOption);
    },

    async getData() {
      const { data } = await this.$http.get("/diet/admin/analytics");
      this.userCount = data.userCount;
      this.analytics = data.analytics;

      // 饼图处理
      const map = {
        DIET_LOG: "饮食打卡",
        NUTRITION_ANALYSIS: "营养分析",
        NUTRITION_EDUCATION: "营养教育",
        ANTI_INFLAMMATORY_RANKING: "抗炎食物推荐",
        PROFILE_VIEW: "我的信息"
      };
      this.clickOption.series[0].data = this.analytics
        .filter(item => map[item.eventType])
        .map(item => ({
          name: map[item.eventType],
          value: item.count,
          click_count: item.count
        }));
      this.clickEchart?.setOption(this.clickOption);

      // 折线图处理
      const { hours, counts } = this.getDietLogSeriesData();
      this.contentOption.xAxis.data = hours;
      this.contentOption.series[0].data = counts;
      this.contentEchart?.setOption(this.contentOption);
    }
  },

  async mounted() {
    await this.getData();
    this.initCharts();

    window.addEventListener("resize", () => {
      this.contentEchart?.resize();
      this.clickEchart?.resize();
    });
  }
};
</script>

<style scoped lang="less">
.box {
  display: flex;
  align-items: center;
  gap: 12px;
  border-radius: 16px;
  justify-content: center;
  color: #ffffff;

  &.user-box {
    padding: 40px 0;
    background-color: #bcdef4;
  }
  &.visit-box {
    padding: 40px 0;
    background-color: #edb6da;
  }
  &.clock-box {
    padding: 40px 0;
    background-color: #ccb3f6;
  }
}

.content-count {
  font-size: 12px;
  margin-bottom: 12px;
}
</style>
